<template>
  <el-dialog v-model="drawer" :append-to-body="true" width="800px" title="新建线索">
    <el-form :model="form" :rules="rules" label-width="110px" class="drawer-form" size="small" :inline="false"
             ref="ruleFormRef">
      <el-form-item label="客户信息识别" prop="lineImg">
        <el-upload class="upload-demo" drag :action="action" :multiple="false" :headers="headers">
          <el-icon class="el-icon--upload">
            <ele-UploadFilled/>
          </el-icon>
          <div class="el-upload__text">
            拖拽上传或 <em>点击上传</em>
          </div>
        </el-upload>
      </el-form-item>
      <el-divider content-position="left">客户基础信息</el-divider>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="intactName">
<!--            <el-select v-model.trim="form.intactName" filterable placeholder="请选择客户(公司)全称" clearable allow-create default-first-option value-key="value" :filter-method="customerSearch" style="width: 230px" @change="customerChange">-->
<!--              <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item"/>-->
<!--            </el-select>-->

            <el-autocomplete
                v-model="intactNameSelect"
                :fetch-suggestions="querySearchAsync"
                placeholder="请选择客户(公司)全称"
                @select="handleIntactNameSelect"
                value-key="name"
                style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="客户简称" prop="nickname">
            <el-input placeholder="请输入客户简称" v-model="form.nickname"/>
          </el-form-item>
          <el-form-item label="客户类型" prop="customerType">
            <el-select v-model="form.customerType" placeholder="请选择客户类型" size="small" style="width: 230px;">
              <el-option label="代理商" :value="0"/>
              <el-option label="直客" :value="1"/>
              <el-option label="代理商客户" :value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item label="级别" prop="levelId">
            <el-select v-model="form.levelId" placeholder="请选择客户级别" size="small" style="width: 230px">
              <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <el-icon :size="16" style="margin-left: 5px;cursor: pointer" color="var(--next-bg-topBarColor)" @click="levelVisible = true">
              <ele-Setting/>
            </el-icon>
          </el-form-item>
          <el-form-item label="外协公司" prop="outCompany">
            <el-input v-model="form.outCompany" placeholder="请填写外协公司" maxlength="128" clearable/>
          </el-form-item>
          <el-form-item label="线索归属部门" prop="deptId">
            <el-select v-model="form.deptId" size="small" style="width: 230px" placeholder="请选择归属部门" clearable @change="getClueUsers">
              <el-option v-for="item in deptList" :key="item.id" :value="item.id" :label="item.name"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分部" prop="branchName">
            <el-input placeholder="请输入分部名称" v-model="form.branchName"/>
          </el-form-item>
          <el-form-item label="上级客户" prop="superiorId">
            <el-select v-model="form.superiorId" placeholder="请选择上级客户" style="width: 230px" clearable filterable>
              <el-option v-for="item in customerList" :key="item.id" :label="item.nickname" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="客户分类" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio :label="0">组织</el-radio>
              <el-radio :label="1">个人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="经营范围" prop="businessScope">
            <el-select v-model="form.businessScope" placeholder="请选择经营范围" style="width:230px">
              <el-option v-for="item in businessList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <el-icon :size="16" title="快捷经营范围设置" style="margin-left:5px;cursor:pointer;" color="var(--next-bg-topBarColor)" @click="businessVisible = true">
              <ele-Setting/>
            </el-icon>
          </el-form-item>
          <el-form-item label="客户阶段" prop="stageId">
            <el-select v-model="form.stageId" placeholder="请选择客户阶段" size="small" style="width: 230px">
              <el-option v-for="item in stageList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="线索归属人" prop="belongId">
            <el-select v-model="form.belongId" placeholder="请选择线索归属人" size="small" style="width: 230px" clearable>
              <el-option v-for="item in belongList" :key="item.userId" :label="item.nickname" :value="item.userId"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="sourceChannel" label="客户来源" style="margin-top: 18px">
        <el-select v-model="form.sourceChannel" placeholder="请选择渠道" size="small" @change="channelChange" clearable filterable style="width: 230px">
          <el-option v-for="item in sourceList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
        <el-select v-model="form.sourceScene" :placeholder="form.sourceChannel ? '请选择来源场景' : '请先选择来源渠道'" :disabled="!form.sourceChannel" size="small" filterable clearable style="margin-left: 10px;width: 230px">
          <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
        <el-icon :size="16" title="来源设置" style="margin-left:5px;cursor:pointer" color="var(--next-bg-topBarColor)" @click="sourceVisible = true">
          <ele-Setting/>
        </el-icon>
      </el-form-item>
      <el-form-item label="客户经理" prop="managerId">
        <el-select v-model="form.managerId" placeholder="请选择客户经理" style="width: 230px" clearable filterable>
          <el-option v-for="item in enterpriseUsers" :key="item.userId" :value="item.userId" :label="item.nickname"/>
        </el-select>
      </el-form-item>

      <div v-for="(item, index) in form.contacts" :key="item.id" style="margin: 18px 0;">
        <el-row class="row-item">
          <el-col :span="12">
            <el-form-item prop="contactName" :label="`联系人${index + 1}`">
              <el-input placeholder="请输入联系人" v-model="item.name"></el-input>
            </el-form-item>
            <el-form-item prop="contactJob" label="职位" style="margin-top: -10px;">
              <el-input placeholder="请输入联系人的职位" v-model="item.job"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="role" label="角色">
              <el-input placeholder="请填写联系人角色" v-model="item.role"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" style="width:270px;margin-top:-10px">
              <el-input placeholder="请输入联系电话" :maxlength="11" :minlength="11" @blur="checkContactPhone(item)" v-model="item.phone"/>
              <el-checkbox v-model="item.isWechat" label="wei" size="small" :true-label="0" :false-label="1" style="margin-right: 10px;">微信同号</el-checkbox>
              <el-checkbox v-model="item.isMain" label="wei" @change="onIsMainEvent(item)" size="small" :true-label="0" :false-label="1">主要联系人</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-left:110px;margin-top: -18px" v-if="(form.contacts.length == 1 || (form.contacts.length > 1 && index > 0))">
          <el-icon :size="16" v-if="(index === form.contacts.length - 1)" color="var(--el-color-primary)" style="margin-right:5px;margin-left:5px;cursor:pointer;margin-top:4px;" @click="addContact">
            <ele-CirclePlus/>
          </el-icon>
          <el-icon :size="16" color="var(--el-color-danger)" style="margin-right:5px;margin-left:5px;cursor:pointer;margin-top:4px;" v-if="index > 0" @click="delContact(index)">
            <ele-Remove/>
          </el-icon>
        </el-row>
      </div>

      <el-form-item prop="remark" label="备注" class="remark-item">
        <el-input type="textarea" v-model="form.remark"></el-input>
      </el-form-item>

      <el-divider content-position="left">机会信息</el-divider>

      <el-row style="margin-bottom: 18px">
        <el-col :span="12">
          <el-form-item label="预计签约日期" prop="signDate">
            <el-date-picker style="width: 230px" v-model="form.signDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date" placeholder="请选择预计签约日期" size="small"/>
          </el-form-item>
          <el-form-item label="产品线" prop="productLineName">
            <el-select v-model="form.productLineName" placeholder="请选择产品线" allow-create default-first-option filterable clearable @change="productChange" size="small" style="width: 230px">
              <el-option v-for="item in productLineList" :key="item.name" :label="item.name" :value="item.name"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计签约金额(元)" prop="signAmount">
            <el-input-number v-model="form.signAmount" :min="0" :max="9999999999" style="width: 230px" :controls="false"/>
          </el-form-item>
          <el-form-item label="签约可能性(%)" prop="probability" label-width="92px">
            <el-input-number v-model="form.probability" :min="1" :max="100" style="width: 230px" :controls="false"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="地点定位" prop="location">
        <el-cascader ref="areaTree" v-model="form.area" :options="cityList" :props="props" style="width:89.8%" @change="handleChange"/>
        <el-input placeholder="请输入详细地址" v-model="form.address" style="width:89.8%;margin-top:10px;" @blur="getMarket"></el-input>
        <!--  地图  -->
        <div id="map" ref="map"></div>
      </el-form-item>
    </el-form>

    <!--  客户经营范围设置   -->
    <business-setting v-model:dialog-visible="businessVisible" @callback="getBusinessData"/>
    <!--  客户来源设置  -->
    <source-setting v-model:dialog-visible="sourceVisible" @callback="getSourceData"/>
    <!-- 客户级别设置 -->
    <level-setting v-model:dialog-visible="levelVisible" @callback="getLevelData"/>

    <template #footer>
      <el-button size="small" @click="cancel(ruleFormRef)">取消</el-button>
      <el-button type="primary" size="small" @click="submit(ruleFormRef)">提交</el-button>
    </template>
  </el-dialog>
</template>
<script>
import {computed, reactive, toRefs, getCurrentInstance, shallowRef, ref} from 'vue'
import {city} from '/@/utils/city'
import AMapLoader from '@amap/amap-jsapi-loader'
import {changeDetSelect} from '/@/utils/utils'
import {ElMessage} from 'element-plus'
import {Session} from '/@/utils/storage'
import SourceSetting from './SourceSetting.vue'
import BusinessSetting from './BusinessSetting.vue'
import LevelSetting from '/@/views/crm/components/LevelSetting.vue'
import customerApi from '/@/api/ums/customer'
import {getDeptSelector} from '/@/api/sys/dept'
import levelApi from '/@/api/ums/customer/level'
import sourceApi from '/@/api/ums/customer/source'
import businessApi from '/@/api/ums/customer/business'
import opportunityApi from '/@/api/ums/customer/opportunity'
import {getDeptUsers, getEnterpriseUsers} from '/@/api/sys/user'
import opportunityStageApi from '/@/api/ums/customer/opportunityStage'
import {tianYanChaBaseInfo, tianYanChaSearch} from "../../../api/ums/customer/tianYanCha";

export default {
  name: 'CustomerCreate',
  props: {
    dialogDrawer: {
      type: Boolean,
      default: false
    }
  },
  components: {
    SourceSetting,
    BusinessSetting,
    LevelSetting
  },
  emits: ['callback', 'update:dialogDrawer'],
  setup(props, context) {
    const {proxy} = getCurrentInstance()
    const {dialogDrawer} = toRefs(props)
    let drawer = computed({
      get: () => {
        if (dialogDrawer.value) {
          initMap()
          getLevelData()
          getSourceData()
          getBusinessData()
          getDeptSelector().then(res => state.deptList = res.data)
          opportunityStageApi.getList().then(res => state.stageList = res.data).catch(e => console.log(e))
          getEnterpriseUsers().then(res => state.belongList = state.enterpriseUsers = res.data).catch(e => console.log(e))
          customerApi.getProductLines().then(res => state.productLineList = res.data).catch(e => console.log(e))
          customerApi.getList().then(res => state.customerList = res.data).catch(e => console.log(e))
        }
        return dialogDrawer.value
      },
      set: (val) => {
        context.emit('update:dialogDrawer', val)
      }
    })
    let map = shallowRef(null)
    let marker = shallowRef(null)
    let geocoder = null
    let Map = null
    const ruleFormRef = ref()
    let timeout = ref(null)
    const state = reactive({
      action: '/api/file/filaAttach/upload',
      headers: {
        '17work': Session.get('token')
      },
      tianYanChaForm:{
        keyword:null,
        current:1,
        size:20
      },
      intactNameSelect:'',
      businessForm:{
        id: null,
        name: null
      },
      form: {
        id: null,
        type: 0,  // 客户分类, 0组织 1个人
        contacts: [{index: 0, name: null, phone: null, isWechat: 0, isMain: 1, role: null, job: null}],
        outCompany: null,
        intactName: null,
        branchName: null,
        levelId: null,
        deptId: null,
        belongId: null,
        signTotal: 1,
        areaDetail: [],
        sourceChannel: null,// 客户来源渠道
        sourceScene: null,
        managerName: null,
        expectedSignAmount: 0,
        role: '', //联系人角色
        address: null,  // 地址全称
        addrCode: null,   // 省市区地址编码, 逗号隔开
        addrName: null,   // 省市区地址, 逗号隔开
        lng: null,    // 经度
        lat: null,    // 纬度
        productLineId: null,    // 产品线id
        productLineName: null   // 产品线名称
      },
      rules: {
        nickname: {required: true, message: '请输入客户简称', trigger: 'blur'},
        intactName: {required: true, message: '请输入客户全称', trigger: 'blur'},
        productLineName: {required: true, message: '请选择产品线', trigger: 'change'}
        // phone: [
        //   {required: true, message: '请输入手机号', trigger: 'blur'},
        //   {pattern: /^[1]([3-9])[0-9]{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        // ]
      },
      companyList: [],  // 公司名称, 从xxx获取
      deptList: [],   // 线索归属部门选择器列表
      levelList: [],  // 客户级别
      customerList: [],   // 上级客户列表
      belongList: [],   // 线索归属人列表
      enterpriseUsers: [],  // 企业用户列表
      businessList: [],
      parentCustomerList: [],
      sourceList: [],
      sceneList: [],
      stageList: [],
      roleList: [], // 联系人角色列表
      // 客户类型下拉列表
      typeList: [],
      otherCompanyList: [],
      // 产品线下拉列表
      productLineList: [],
      cityList: city,
      loading: false,
      props: {
        expandTrigger: 'hover',
        value: 'code'
      },
      // cuesBelongList: [],
      customerManageList: [],
      sourceVisible: false,   // 来源表格显隐
      businessVisible: false,   // 客户经营范围设置
      levelVisible: false,    // 客户级别设置
      dialogCustomer: false,// 选择代理商
      dialogScene: false,//
      dialogCustomerType: false,
      // dialogProduct: false,
      dialogBelong: false,// 控制选择线索归属人
    })

    const getSourceData = () => sourceApi.sourceSelector().then(res => state.sourceList = res.data).catch(e => console.log(e))
    const getBusinessData = () => businessApi.businessSelector().then(res => state.businessList = res.data).catch(e => console.log(e))
    const getLevelData = () => levelApi.levelList().then(res => state.levelList = res.data).catch(e => console.log(e))
    // 检查是否是手机号
    const checkContactPhone = (e) => {
      if (!e) return false
      if (!e.phone) return false
      const testMobileValue = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (testMobileValue.test(e.phone))
        return true
      ElMessage.error('请输入正确的手机号')
      return false
    }
    // 客户经理 - 添加选择
    const selectCustomerManageEvent = obj => {
      const {id, name} = obj
      state.form.managerId = id
      state.form.managerName = name
    }
    // 获取线索归属人
    const getClueUsers = (deptId) => {
      if (deptId) {
        getDeptUsers(deptId).then(res => state.belongList = res.data).catch(e => console.log(e))
      } else {
        state.belongList = state.enterpriseUsers
      }
    }
    // 点击设置为空主要联系人
    const onIsMainEvent = (e) => {
      // 检查是不是当前为空默认联系人，然后点击取消不为联系人，但是当前数组上没有默认联系人情况下
      // 对当前取消不为默认联系操作禁止
      const index = state.form.contacts.findIndex(fe => fe.isMain === 0)
      if (index === -1) {
        e.isMain = 0
        ElMessage.warning('当前已是默认联系人')
      } else {
        // 循环将选中的移除
        state.form.contacts.forEach(fe => {
          if (fe.index === e.index)
            return
          fe.isMain = 1
        })
      }
    }
    const addContact = () => {
      state.form.contacts.push({
        index: state.form.contacts.length + 1, // 往前推
        name: null,
        phone: null,
        isWechat: 0,
        isMain: 1,
        role: null,
        job: null
      })
    }
    const delContact = e => state.form.contacts.splice(e, 1)
    // 点击选择地址
    const handleChange = async () => {
      state.form.areaDetail = proxy.$refs['areaTree'].getCheckedNodes()[0].pathLabels
      // 选择地址后激活信息地址框
    }
    const initMap = () => {
      AMapLoader.load({
        key: '54258384f8ac03ec2032977d0a45e678',             // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0',      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geolocation', 'AMap.LngLat', 'AMap.Marker', 'AMap.Pixel', 'AMap.Geocoder']       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        Map = AMap
        map = new AMap.Map('map', {  //设置地图容器id
          zoom: 16
        })
        let geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000
        })
        geolocation.getCityInfo((status, result) => {
          if (status == 'complete') {
            // eslint-disable-next-line vue/no-ref-as-operand
            map.setCenter(new AMap.LngLat(result.position[0], result.position[1]))
            marker = new AMap.Marker({
              icon: '/src/assets/position.png',
              position: result.position,
              offset: new AMap.Pixel(-13, -30)
            })
            // eslint-disable-next-line vue/no-ref-as-operand
            marker.setMap(map)
          } else {
              // eslint-disable-next-line vue/no-ref-as-operand
              map.setCenter(new AMap.LngLat(113.295799, 23.035493))
              marker = new AMap.Marker({
                icon: '/src/assets/position.png',
                position: [113.295799, 23.035493],
                offset: new AMap.Pixel(-13, -30)
              })
              // eslint-disable-next-line no-console
            }
            console.log('error => ', result)
        })
        geocoder = new AMap.Geocoder()
        // eslint-disable-next-line vue/no-ref-as-operand
        map.on('click', (result) => {
          const lng = result['lnglat'].getLng()
          const lat = result['lnglat'].getLat()
          state.form.lng = lng
          state.form.lat = lat
          // eslint-disable-next-line vue/no-ref-as-operand
          marker.setPosition(new AMap.LngLat(lng, lat))
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // result为对应的地理位置详细信息
              // console.log("地图回调数据=>", result);
              const addressComponent = result['regeocode']['addressComponent']
              const {district, city, province} = addressComponent
              const codeArray = changeDetSelect(addressComponent.adcode, state.cityList, 'code')
              state.form.area = codeArray
              //    省/市/区(县)
              state.form.addrName = province + ',' + city + ',' + district
              state.form.addrCode = codeArray[0] + ',' + codeArray[1] + ',' + codeArray[2]
              // 地址全称
              state.form.address = result['regeocode']['formattedAddress']
            }
          })
        })
      }).catch(e => {
        // eslint-disable-next-line no-console
        console.log(e)
      })
    }
    const getMarket = (isUpdateMap) => {
      geocoder.getLocation(state.form.areaDetail.join('') + state.form.address, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          // eslint-disable-next-line vue/no-ref-as-operand
          map.setCenter(new Map.LngLat(result['geocodes'][0].location.lng, result['geocodes'][0].location.lat))
          // eslint-disable-next-line vue/no-ref-as-operand
          marker.setPosition(new Map.LngLat(result['geocodes'][0].location.lng, result['geocodes'][0].location.lat))
          if(isUpdateMap !== undefined){
            simulateClick(result)
          }
        }
      })
    }
    const submit = async (formEl) => {
      if (!formEl) return
      await formEl.validate(async (valid) => {
        if (!valid) return // 必填没有填就直接结束
        try {
          // console.log(state.form);
          // 如果为空不检查
          // 有填入就校验
          // 检查联系人手机号是否正确
          state.form.contacts.forEach((f, index) => {
            if (f.phone || f.phone !== '') {
              const testMobileValue = /^[1][3,4,5,6.7,8,9][0-9]{9}$/
              if (!testMobileValue.test(f.phone))
                throw new Error('联系人' + (index + 1) + '的手机号不正确，请输入正确的手机号')
            }
          })
          // 发起请求处理添加
          const {data} = await opportunityApi.createData(state.form)
          ElMessage.success(data)
          // 调用父组件刷新列表
          context.emit('callback')
          // 刷新抽屉状态
          context.emit('update:dialogDrawer', false)
          drawer = false
          state.form = {
            id: null,
            type: 0,
            contacts: [{index: 0, name: null, phone: null, isWechat: 0, isMain: 0, role: null, job: null}],
            outCompany: null,
            intactName: null,
            branchName: null,
            levelId: null,
            deptId: null,
            belongId: null,
            signTotal: 1,
            areaDetail: [],
            sourceChannel: undefined,// 客户来源 - 渠道
            // cuesBelong: null,
            managerName: null,
            expectedSignAmount: 0,
            role: '', //联系人角色
            address: null,  // 地址全称
            addrCode: null,   // 省市区地址编码, 逗号隔开
            addrName: null,   // 省市区地址, 逗号隔开
            lng: null,    // 经度
            lat: null,    // 纬度
            productLineId: null,    // 产品线id
            productLineName: null   // 产品线名称
          }
        } catch (e) {
          ElMessage.error(e.message)
        }
      })
    }
    // 关闭
    const cancel = (formEl) => {
      if (!formEl) return
      formEl.resetFields()
      context.emit('update:dialogDrawer', false)
    }
    // 来源渠道改变
    const channelChange = (e) => {
      // 清空具体场景
      state.form.sourceScene = null
      if (e) {
        // 加载二级来源数据
        sourceApi.sourceSelector(e).then(res => state.sceneList = res.data).catch(e => console.log(e))
      } else {
        state.sceneList = []
      }
    }
    const openCustomerType = () => state.dialogCustomerType = true
    // 从服务器搜索对应客户
    const customerSearch = (val) => {
      console.log(val)
    }
    // 客户改变
    const customerChange = (item) => {
      // 保存客户统一社会信用代码 全称？
      console.log(item)
    }

    // 选中某个产品
    const productChange = (productName) => {
      state.form.productLineId = null
      for (let i = 0; i < state.productLineList.length; i++) {
        let item = state.productLineList[i]
        if (item.name == productName && item.id) {
          state.form.productLineId = item.id
          break
        }
      }
    }

    //选中公司选项
    const handleIntactNameSelect = (item) => {
      if(item.creditCode){ //社会统一信用码
        tianYanChaBaseInfo({keyword:item.creditCode}).then(res =>{
          if(res.data){
            state.form.intactName = item.name  //全称
            state.form.nickname = res.data.alias  //简称
            let index = state.form.contacts.length - 1 < 0 ? 0 : state.form.contacts.length -1;
            if(state.form.contacts[index].name == null && state.form.contacts[index].phone == null && state.form.contacts[index].role == null && state.form.contacts[index].job == null){
              state.form.contacts[index].phone = res.data.phoneNumber //号码
              state.form.contacts[index].name = res.data.legalPersonName //法人名称
              state.form.contacts[index].role = "法人" //角色
            }else{
              addContact()
              index = state.form.contacts.length - 1 < 0 ? 0 : state.form.contacts.length - 1;
              state.form.contacts[index].phone = res.data.phoneNumber //号码
              state.form.contacts[index].name = res.data.legalPersonName //法人名称
              state.form.contacts[index].role = "法人" //角色
            }
            var isCreateBusiness = true
            for (let i = 0; i < state.businessList.length; i++) {
              if(state.businessList[i].name.indexOf(res.data.industry) >= 0){
                //存在
                isCreateBusiness = false
                state.form.businessScope = state.businessList[i].id
              }
            }
            if(isCreateBusiness){
              state.businessForm.name = res.data.industry //经营范围
              businessApi.createBusiness(state.businessForm).then(res =>{ //直接添加
                getBusinessData().then(()=>{
                  state.form.businessScope = state.businessList[0].id
                })
              })
            }
            state.form.address = res.data.regLocation //注册地址
            getMarket(true) //执行地址搜索
          }
        })
      }
    }

    //从后台获取自动补全的数据
    const querySearchAsync = (queryString, cb) => {
      var restaurants = []
      state.tianYanChaForm.keyword = queryString
      if(queryString == null || queryString === ''){
        cb(restaurants);
        return;
      }
      tianYanChaSearch(state.tianYanChaForm).then(res =>{
        state.companyList = res.data
        restaurants = res.data
        let results = queryString ? restaurants.filter(createStateFilter(queryString)) : restaurants;
        clearTimeout(timeout.value);
        timeout.value = setTimeout(() => {
          cb(results);
        }, 3000 * Math.random());
      })
    }

    //自动补全过滤
    const createStateFilter = (queryString) => {
      return (state) => {
        return (state.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      }
    }

    //模拟点击地图
    const simulateClick = (result) => {
      const lng = result['geocodes'][0].location.lng
      const lat = result['geocodes'][0].location.lat
      state.form.lng = lng
      state.form.lat = lat
      // eslint-disable-next-line vue/no-ref-as-operand
      marker.setPosition(new AMap.LngLat(lng, lat))
      geocoder.getAddress([lng, lat], function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          // result为对应的地理位置详细信息
          // console.log("地图回调数据=>", result);
          const addressComponent = result['regeocode']['addressComponent']
          const {district, city, province} = addressComponent
          const codeArray = changeDetSelect(addressComponent.adcode, state.cityList, 'code')
          state.form.area = codeArray
          //    省/市/区(县)
          state.form.addrName = province + ',' + city + ',' + district
          state.form.addrCode = codeArray[0] + ',' + codeArray[1] + ',' + codeArray[2]
          // 地址全称
          state.form.address = result['regeocode']['formattedAddress']
        }
      })
    }

    return {
      timeout,
      drawer,
      ...toRefs(state),
      addContact,
      delContact,
      handleChange,
      map,
      getMarket,
      ruleFormRef,
      submit,
      cancel,
      openCustomerType,
      channelChange,
      onIsMainEvent,
      selectCustomerManageEvent,// 客户经理
      checkContactPhone,// 检查手机号
      productChange, // 选择产品线
      customerSearch,
      getClueUsers,
      customerChange,
      getSourceData,
      getBusinessData,
      getLevelData,
      handleIntactNameSelect,
      querySearchAsync,
      createStateFilter,
      simulateClick
    }
  }
}
</script>
<style scoped lang="scss">
.drawer-form {
  padding: 10px 10px 64px;

  .upload-demo {
    width: 89.8%;

    :deep(.el-upload-dragger) {
      padding: 5px 0;
    }

    :deep(.el-upload__text) {
      margin-top: -15px;
    }
  }

  :deep(.el-form-item) {
    align-items: flex-start;
  }

  .row-item {
    // margin-bottom: 10px;

    :deep(.el-form-item:nth-child(2) .el-input__wrapper) {
      width: 116px;
    }
  }

  .remark-item {
    :deep(.el-textarea__inner) {
      width: 430px;
    }
  }

  #map {
    width: 89.8%;
    height: 150px;
    margin-top: 10px;
  }
}

/* 禁止鼠标选中字体
------------------------------- */
.ss-us-n {
  /* 火狐 */
  -moz-user-select: none !important;
  /* Safari 和 欧朋 */
  -webkit-user-select: none !important;
  /* IE10+ and Edge */
  -ms-user-select: none !important;
  /* Standard syntax 标准语法(谷歌) */
  user-select: none !important;
}
</style>
